// @ts-ignore
//初始化项目插件
import Application  from "koa";
import bodyparser from 'koa-bodyparser';
import json from 'koa-json';  
import logger from 'koa-logger';  //请求日志
// @ts-ignore
import onerror from 'koa-onerror'
import staticPublic from 'koa-static';

import config  from "../config/init";
import{ ConfigType }  from '../config/init';
import { DataSource } from "typeorm";
import { MysqlConnectionOptions } from "typeorm/driver/mysql/MysqlConnectionOptions";


export class init{
    private plugin: Array<Application.Middleware<Application.DefaultState & { },  Application.DefaultContext & {}>> = [];
    protected koa:Application =new Application()
    protected config: ConfigType =<ConfigType><unknown>config;
    protected orm!:DataSource;
    constructor(){
        this.initPlugin()
    }

    initPlugin(){
       onerror(this.koa);
       this.config.orm = new DataSource(<MysqlConnectionOptions>this.config.mysql)
        this.config.orm.initialize()
        this.plugin=[
            bodyparser({
                enableTypes:['json', 'form', 'text']
            }),
            json(),
            logger(),
            staticPublic(__dirname + config.staticPath),
            // async (ctx, next) => {
            //     const start = new Date().valueOf()
            //     await next()
            //     const ms = new Date().valueOf() - start
            //     console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
            // }
        ]
        this.usePlugin()
    }

    usePlugin(){
        //挂载插件数组到Koa内部
        this.plugin.forEach(v=>{
            this.koa.use(v)
        })
    }
}